package com.otto.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.otto.reggie.common.BaseContext;
import com.otto.reggie.common.R;
import com.otto.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求过滤器
 * 作者：otto
 * 时间：2022-07-20 15:06:30
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //工具匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        //强制转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //日志输出拦截到的请求
        String requestURI = request.getRequestURI();
        log.info("拦截到请求 {}", requestURI);
        //定义不需要拦截的请求
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //利用匹配器判断请求是否需要处理
        boolean check = check(urls, requestURI);
        if (check) {
            filterChain.doFilter(request, response);
            log.info("{} 请求不需要处理", requestURI);
            return;
        }

        //员工登录判断
        if (request.getSession().getAttribute("employee") != null) {
            log.info("id为 {} 的用户已登录，放行请求 {}", request.getSession().getAttribute("employee"), requestURI);

            Long id = Thread.currentThread().getId();
            log.info("线程id为 {}",id);
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }
        //移动端用户登陆判断
        if (request.getSession().getAttribute("user") != null) {
            log.info("id为 {} 的用户已登录，放行请求 {}", request.getSession().getAttribute("user"), requestURI);

            Long id = Thread.currentThread().getId();
            log.info("线程id为 {}",id);
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }
        log.info("请求 {} 需要处理，且用户未登录", requestURI);
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;


    }

    //检查是否匹配
    public boolean check(String[] us, String url) {
        for (String s : us) {
            boolean match = PATH_MATCHER.match(s, url);
            if (match) {
                log.info("{} 和 {} 匹配", s, url);
                return true;
            }
        }
        log.info("{} 和 {} 不匹配", us, url);
        return false;
    }
}
